<?php

include_once 'facebook.php';
// the facebook client library
include_once 'facebook_desktop.php';

/*
 * Builds the command to run genstrings with.
 */
function build_cmd($dir_name, $input) {
  $function_name = "FBLocalizedString";
  $cmd = "genstrings";
  $cmd .= " -o $dir_name";
  $cmd .= " -s $function_name";
  $cmd .= " $input";
  return $cmd;
}

// Expects a line like this: 
//  /* Description */ 
function extract_description($line) {
  $pattern = "%(^/\*)(.*)(\*/$)%";
  $groups = array();
  $match = preg_match($pattern, $line, $groups);
  if (!$match) {
    return null;
  }
  return trim($groups[2]);
}

/* 
 * Expects a line roughly like this:
 * "Hello" = "Hello"
 * Returns the first string. Works fine with escaped quotes in the first string.
 */

function extract_string($line) {
  $pattern = "%(^\s*\")(.*)(\"\s*=\s*.*)%";
  $groups = array();
  $match = preg_match($pattern, $line, $groups);
  if (!$match) {
    return null;
  }
  return $groups[2];
}

function unescape_c_string($string) {
  return stripcslashes($string);
}

function unescape_c_strings($strings) {
  $escaped = array();
  foreach ($strings as $text_desc_pair) {
    $text = unescape_c_string($text_desc_pair['text']);
    $desc = unescape_c_string($text_desc_pair['description']);
    $escaped[] = array('text' => $text, 'description' => $desc);
  }
  return $escaped;
}

/*
 * Parses genstrings' output and returns the result.
 */
function get_genstrings_output($file_path) {
  $strings = array();
  $file = fopen($file_path, "r");
  if (!$file) {
    echo "Failed to open genstrings' output files. Exiting.\n";
    exit();
  }
  while (!feof($file)) {
    $line = fgets($file);
    // Two lines at a time or ignore
    if (feof($file)) {
      break;
    }
    $desc = extract_description($line);
    if ($desc == null) {
      continue;
    }
    $line = fgets($file);
    $string = extract_string($line);
    if ($string == null) {
      continue;
    }
    $strings[] = array("text" => $string,
                       "description" => $desc);
  }
  fclose($file);
  return $strings;
}

/*
 *  Converts the file generated by genstrings back into ISO-8859-1 from 
 *  UTF-16 and returns the path to the new file.
 */
function get_fixed_encoding_file($dir_name) {
  $file_path = $dir_name . "/" . "Localizable.strings";
  $fixed_file_path = "$file_path.iso_8859_1";
  $cmd = "iconv -f UTF-16 -t ISO-8859-1";
  $cmd .= " $file_path > $fixed_file_path";
  `$cmd`;
  return $fixed_file_path;
}

/*
 * Extracts the strings from the given source files using Apple's 
 * genstrings utility and returns the text-description pairs in
 * an array of arrays.
 */
function get_strings($input) {
  $dir_name = "fbStrings_" . rand();
  $mkdir_out = `mkdir $dir_name`;
  if (!empty($mkdir_out)) {
    $error = "Error creating temp folder. ";
    $error .= "Make sure you have write permissions in the directory you ";
    $error .= "run this script in. Exiting.\n";
    echo $error;
    exit();
  }
  $cmd = build_cmd($dir_name, $input);
  `$cmd`;
  $file_path = get_fixed_encoding_file($dir_name);
  $strings = get_genstrings_output($file_path);
  // Clean up
  `rm -rf $dir_name`;
  return $strings;
}

function print_strings($strings) {
  foreach ($strings as $pair) {
    echo $pair["text"] . " : " . $pair["description"] . "\n";
  }
}

function build_url($api_key, $auth_token) {
  $success_url = "http://www.facebook.com/connect/login_success.html";
  $params = array('api_key' => $api_key,
                  'v' => '1.0',
                  'auth_token' => $auth_token,
                  'fbconnect' => 'true',
                  'return_session' => 'true',
                  'next' => $success_url,
                  'session_key_only' => 'true');

  $params_string = http_build_query($params);
  $login_url = "http://www.facebook.com/login.php?" . $params_string;
  return $login_url;
}

function upload_strings($api_key, $secret, $input) {
  $strings = get_strings($input);

  print_strings($strings);
  $cnt = count($strings);
  if ($cnt < 1) {
    echo "No strings found. Exiting.\n";
    exit();
  }
  echo "\nThe $cnt string(s) above will be uploaded.\n";
  echo "To exit now, use Ctrl-C.\n";

  $facebook = new FacebookDesktop($api_key, $secret);
  $auth_token = $facebook->api_client->auth_createToken();
  $login_url = build_url($api_key, $auth_token);
  `open "$login_url"`;

  do {
    echo "Otherwise, type 'y' to continue after logging into Facebook.\n";
  } while (!(strtolower(fgets(STDIN)) === "y\n"));

  if(null == $facebook->do_get_session($auth_token)) {
    echo "Could not obtain Facebook session. Exiting.\n";
    exit();
  }

  $unescaped_strings = unescape_c_strings($strings);
  $num_strings =
    $facebook->api_client->intl_uploadNativeStrings($unescaped_strings);
  if (!$num_strings) {
    echo "Oops. Sorry, failed to upload.\n";
  } else {
    echo "$num_strings string(s) uploaded successfully.\n";
  }
}

function arg_proc(&$arg, $arg_name, $i, $argv, $argc) {
  if ($argv[$i] === "-" . $arg_name || $argv[$i] === "--" . $arg_name) {
    if ($i + 1 < $argc) {
      $arg = $argv[$i + 1];
    }
  }
}

function print_usage() {
  $usage = "Usage:   php string_upload.php -api_key YOUR_API_KEY -secret YOUR_SECRET ";
  $usage .= "-input \"INPUT_FILE_NAME_PATTERN\"\n";
  $usage .= "Example: php string_upload.php -api_key 917fa73fa6ed72e81e4d1507157a9dea ";
  $usage .= "-secret cc44079a45c179843c34d923b40ad116 -input \"Classes/*.m\"\n";
  echo $usage;
}

$api_key = "";
$secret = "";
$input = "";

for ($i = 0; $i < $argc; $i++) {
  arg_proc($api_key, "api_key", $i, $argv, $argc);
  arg_proc($secret, "secret", $i, $argv, $argc);
  arg_proc($input, "input", $i, $argv, $argc);
}

if (empty($api_key) || empty($secret) || empty($input)) {
  print_usage();
} else {
  upload_strings($api_key, $secret, $input);
}
